package com.tgy.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: tgy
 * @Date: 12/18/20 1:36 PM
 */
public class _46_全排列_01 {

    public List<List<Integer>> permute(int[] nums) {

        List<List<Integer>> rets = new ArrayList<List<Integer>>();
        if (nums == null || nums.length == 0) {

            return rets;
        }

        search(nums,0,rets);
        return rets;
    }

    private void  search(int[] nums, int level, List<List<Integer>> rets) {

        if (level == nums.length) {

            rets.add(Arrays.stream(nums).boxed().collect(Collectors.toList()));
            return;
        }

        for (int i = level; i < nums.length; i++) {

            swap(nums,level,i);
            search(nums,level + 1,rets);
            swap(nums,level,i);
        }

    }

    private void swap(int[] nums, int i1,int i2) {

        if (i1 == i2) {
            return;
        }

        int tmp = nums[i1];
        nums[i1] = nums[i2];
        nums[i2] = tmp;
    }

}
